<?php


namespace App\Admin\Actions\Post;


use App\Exceptions\MsgException;
use App\Extensions\Action;
use App\Models\Department;
use App\Patent;
use App\Services\PatentService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ImportPatentPost extends Action
{
    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        //Excel::import(new PatentImport(), $request->file('file'));
        $types = array_flip(patent_type_select_option());
        $departments = Department::query()->pluck('id', 'name');
        $collect = Excel::toCollection(collect([]), $request->file('file'))->first();
        $collect = collect($collect)->filter(function ($item, $key) {
            return !empty($item[0]) && !empty($item[1]) && !empty($item[0]) && $key;
        });
        $errors = [];
        $collect = $collect->map(function ($row) use ($types, $departments, &$errors) {
            $patent_sn = strtr(trim($row[0]), ["\r" => '', "\t" => '', " " => '', " " => '']);
            $patent_type = strtr(trim($row[2]), ["\r" => '', "\t" => '', " " => '', " " => '']);
            $patent_type_id = $types[$patent_type] ?? 0;
            try {
                $patent_sn = PatentService::check_patent_sn($patent_sn, $patent_type_id);
            } catch (MsgException $exception) {
                $errors[] = $row[0] . ":" . $exception->getMessage();
            }
            return [
                'key'   => $patent_sn,
                'value' => [
                    'patent_sn'        => $patent_sn,
                    'patent_name'      => $row[1],
                    'patent_type_id'   => $patent_type_id,
                    'apply_date'       => excel_import_date(trim($row[3])),
                    'publication_num'  => trim($row[4]),
                    'publication_date' => excel_import_date(trim($row[5])),
                    'applicant'        => trim($row[6]),
                    'inventor'         => trim($row[7]),
                    'department_id'    => $departments->get(trim($row[8]), 0),
                    'legal_status'     => trim($row[9]),
                    'state'            => 1,
                    'created_at'       => Carbon::now(),
                    'updated_at'       => Carbon::now(),
                ]
            ];
        })->pluck('value', 'key');
        if ($errors) {
            return $this->response()->swal()->error(implode("\n", $errors))->refresh();
        }
        $patent_sns = Patent::query()->whereIn('patent_sn', $collect->keys())->pluck('patent_sn', 'patent_sn');
        $collect = $collect->filter(function ($item, $key) use ($patent_sns) {
            return !$patent_sns->get($key);
        })->values();
        $count = $collect->count();
        if ($count > 0) {
            $collect->chunk(100)->map(function ($items) {
                DB::table('patents')->insert($items->all());
            });
        }
        $msg = "导入成功\n\n新增:" . $count;
        return $this->response()->swal()->success($msg)->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件')
            ->help('<a href="/template/patent-import.xlsx" download="新增专利模板" target="_blank">新增专利模板</a>');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post">导入专利</a>
HTML;
    }

}
